(function (Vue) {
	'use strict';
	//使用localstorage 进行本地存储
	let STOREGE_KEY = "todo-items"
	const itemStorage = {
		//获取本地数据的方法:
		fetch(){
			return JSON.parse(localStorage.getItem(STOREGE_KEY) || '[]')
		},
		//保存本地数据的方法
		save(data){
			localStorage.setItem(STOREGE_KEY,JSON.stringify(data))
		}
	}
	var vm = new Vue({
		el:"#todoapp",
		data:{
			// items:[
			// 	{id:1,content:'aaaa',completed:false},
			// 	{id:2,content:'bbbb',completed:false},
			// 	{id:3,content:'cccc',completed:false},
			// 	{id:4,content:'dddd',completed:false}
			// ],

			//转成本地存储:
			items:itemStorage.fetch(),

			currentItem:null,
			filterState:'all'
		},
		methods:{
			addItem(event){
				//获取点击目标事件的值，这里做下去重处理
				let newValue = event.target.value.trim()
				if (!newValue.length){return}
				let newitem = {
					id:this.items.length+1,
					content:newValue,
					completed:false
				};
				this.items.push(newitem)
				event.target.value = ""
			},
			removeItem(index){
				//移除对象 splice()，传入移除对象的索引，以及从此处开始完后删掉的数量
				this.items.splice(index,1)
			},

			//双击编辑:
			toEdit(item){
				this.currentItem = item
			},
			cancelEdit(item,index){		
				this.content = this.items[index].content;
				this.currentItem = null

			},
			saveData(item,index){
				//获取文本框中去除空格后的内容
				let content  = event.target.value.trim()
				//如果将content 内容修改为空，代表想删掉该节点
				if(!content){this.removeItem(index)}

				item.content = content;
				this.currentItem = null
			},
			removeallCompleted(){
				//删除已完成的任务todo
				//使用filter函数:
				this.items = this.items.filter((item) =>{
					return !item.completed
				})
			},

		},
		computed:{
			//计算属性计算未完成项目
			imcompeleted(){
				return this.items.filter((item) => !item.completed).length
			},
			//计算全选
			isSelectAll:{
				set(newState){this.items.forEach((item) => { item.completed = newState})},
				get(){return this.imcompeleted === 0}
			},
			//计算显示项:
			filterItems(){
				//问题关键在于根据hash 读取filterState，见onhashchange函数
				switch (this.filterState) {
					case "active":
						return this.items.filter(item => !item.completed)
						break;
					case "completed":
						return this.items.filter(item => item.completed)
						break;
					default:
						return this.items
						break;
				}
			}
		},
		watch:{
			items:{
				deep:true,
				handler(newitems,olditems){
					itemStorage.save(newitems)
				}
			}
		},
		//增加watch方法，一旦items 值发生变化
		//自定义局部指令:
		directives:{
			// "todo-focus":{
			// 	update(el,binding){
			// 		if(binding.value){el.focus()}
			// 	}
			// },

			//实现自定义指令自动聚焦....
			"focus":{
				inserted(el){
					el.focus()
				}
			}
		}
	})
	// Your starting point. Enjoy the ride!

	//系统hash 时改变时调用函数
	window.onhashchange = function () {
		const  hash = window.location.hash.substr(2) //"#/active"
		//将拿到的hash值回复给vm中的filterState
		vm.filterState = hash
	}
	window.onhashchange()
})(Vue);

